package cn.xaut.动态规划;

import java.util.Arrays;

/**
 * 64. 最小路径和
 */
public class demo64 {

    int[][] memo;
    public int minPathSum(int[][] grid) {

        int m = grid.length;
        int n = grid[0].length;
        memo = new int[m][n];
        for (int[] row : memo)
            Arrays.fill(row, -1);
        
        return dp2(grid, m - 1, n - 1);
    }

    // 从左上角位置(0, 0)走到位置(i, j)的最小路径和为dp(grid, i, j)
    public int dp(int[][] grid, int i, int j) {
        
        // 递归终止条件
        if (i == 0 && j == 0)
            return grid[0][0];
        if (i < 0 || j < 0)
            return Integer.MAX_VALUE;
        
        // 递归过程
        return Math.min(dp(grid, i - 1, j), dp(grid, i, j - 1)) + grid[i][j];
    }

    // 带有备忘录的动态规划
    // 递归解法
    public int dp2(int[][] grid, int i, int j) {
        
        // 递归终止条件
        if (i == 0 && j == 0)
            return grid[0][0];
        if (i < 0 || j < 0)
            return Integer.MAX_VALUE;
        if (memo[i][j] != -1)
            return memo[i][j];

        // 递归过程
        memo[i][j] = Math.min(dp(grid, i - 1, j), dp(grid, i, j - 1)) + grid[i][j];
        return memo[i][j];
    }

    // 迭代解法
    public int minPathSum2(int[][] grid) {

        int m = grid.length;
        int n = grid[0].length;
        int[][] dp = new int[m][n];

        // 基础状态
        dp[0][0] = grid[0][0];
        for (int i = 1; i < m; i ++)
            dp[i][0] = dp[i - 1][0] + grid[i][0];
        for (int j = 1; j < n; j ++)
            dp[0][j] = dp[0][j - 1] + grid[0][j];

        // 状态转移
        for (int i = 1; i < m; i ++){
            for (int j = 1; j < n; j ++)
                dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
        }

        return dp[m - 1][n - 1];
    }

    public static void main(String[] args) {

        System.out.println(new demo64().minPathSum(new int[][]{{1, 3, 1}, {1, 5, 1}, {4, 2, 1}}));
        System.out.println(new demo64().minPathSum(new int[][]{{1, 2, 3}, {4, 5, 6}}));
    }
}
